//
//  WeddingCarCartViewController.m
//  BaseProject
//
//  Created by 王洋 on 2021/5/11.
//  Copyright © 2021 王洋. All rights reserved.
//
#import "WeddingCarCartCell.h"
#import "CommonIntentionModel.h"

#import "WeddingCarCartCell.h"
#import "WeddingCarDetailViewController.h"
#import "WeddingCarCartNotiHeader.h"
#import "MessageCenterViewController.h"
#import "SubmitCarOrderViewController.h"
#import "WeddingCarDetailViewController.h"

#import "WeddingCarCartViewController.h"

@interface WeddingCarCartViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableview;

@property (nonatomic, strong) CommonIntentionModel *intentionModel;

@property (nonatomic, strong)NSMutableArray <WeddingCarCartModel *>*dataArray;

//优惠信息
@property (weak, nonatomic) IBOutlet UILabel *discountLab;

@property (weak, nonatomic) IBOutlet UILabel *fanxianLab;

//合计
@property (weak, nonatomic) IBOutlet UILabel *totalPrice;

@property (weak, nonatomic) IBOutlet UIButton *handleBtn;
@property (weak, nonatomic) IBOutlet UILabel *IntentionLab;

@property (weak, nonatomic) IBOutlet UILabel *totalLab;

@property (weak, nonatomic) IBOutlet UIButton *selectAllBtn;

@property (nonatomic, assign) BOOL isAllSel;

//可购买数量
@property (nonatomic, assign) NSInteger validCount;

@end

@implementation WeddingCarCartViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initView];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self request_cart];
}


- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.handleBtn pp_clipCorners:UIRectCornerAllCorners radius:self.handleBtn.frame.size.height/2];
    });
}

- (void)initView {
    
    self.title = @"我的车队";
    self.isAllSel = NO;
    [self.selectAllBtn setImage:[UIImage imageNamed:self.isAllSel?@"common_sel":@"common_nor"] forState:UIControlStateNormal];

    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    _tableview.showsHorizontalScrollIndicator = NO;
    _tableview.showsVerticalScrollIndicator = NO;
    
    _tableview.estimatedSectionHeaderHeight = 0;
    _tableview.estimatedSectionFooterHeight = 0;
    _tableview.estimatedRowHeight = 0;
    
    _tableview.backgroundColor =  UIColorHex(0xf1f1f1);
    _tableview.showsVerticalScrollIndicator = NO;
    [_tableview registerNib:[UINib nibWithNibName:@"WeddingCarCartCell" bundle:nil] forCellReuseIdentifier:@"WeddingCarCartCellID"];
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setTitle:@"" forState:UIControlStateNormal];
    [rightBtn setImage:[UIImage imageNamed:@"home_msg"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(goMsg) forControlEvents:UIControlEventTouchUpInside];
    rightBtn.frame = CGRectMake(0,0,40,30);
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];

    self.navigationItem.rightBarButtonItems =@[rightItem];
    
    if ([BA_BusinessHelper shared].userProportion == 0) {
        self.fanxianLab.hidden = YES;
    } else {
        self.fanxianLab.hidden = NO;
        self.fanxianLab.text = [NSString stringWithFormat:@"支付立返%ld%%",[BA_BusinessHelper shared].userProportion];
    }
    
    [[TT_MessageManager manager] getTotalUnReadMessage:^(int unReadMsgCount) {}];
    [RACObserve([TT_MessageManager manager], totalUnReadCount) subscribeNext:^(id x) {
        if ([TT_MessageManager manager].totalUnReadCount > 0) {
            rightBtn.badgeValue = [NSString stringWithFormat:@"%d",[TT_MessageManager manager].totalUnReadCount];
            rightBtn.badgeBGColor = [UIColor redColor];
        } else {
            rightBtn.badgeValue = @"";
            rightBtn.badgeBGColor = [UIColor clearColor];
        }
    }];
}

- (void)goMsg {
    MessageCenterViewController *vc = [[MessageCenterViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)selectAllAction:(id)sender {
    
    [self changeAllStatus];
}

- (IBAction)handleAction:(id)sender {
    
    NSMutableArray <WeddingCarCartModel *>*dataArray = @[].mutableCopy;
    for (WeddingCarCartModel *model in self.dataArray) {
        if (model.isSel) {
            [dataArray addObject:model];
        }
    }
    
    if (dataArray.count == 0) {
        [SVProgressHUD showErrorWithStatus:@"请选择一个婚车套餐后再结算"];
        [SVProgressHUD dismissWithDelay:2];
        return;
    }
    
    SubmitCarOrderViewController *vc = [[SubmitCarOrderViewController alloc] init];
    vc.dataArray = dataArray;
    [self.navigationController pushViewController:vc animated:YES];
}

//选择cell选中的时候调用
- (void)refreshSelAllBtnStatus {
    
    NSInteger selCount = 0;
    for (WeddingCarCartModel *model in self.dataArray) {
        if (model.isSel) {
            selCount++;
        }
    }
    if (selCount == self.validCount) {
        [self.selectAllBtn setImage:[UIImage imageNamed:@"common_sel"] forState:UIControlStateNormal];
        self.isAllSel = YES;
    } else {
        [self.selectAllBtn setImage:[UIImage imageNamed:@"common_nor"] forState:UIControlStateNormal];
        self.isAllSel = NO;
    }
}

- (void)changeAllStatus {
    
    self.isAllSel = !self.isAllSel;
    [self.selectAllBtn setImage:[UIImage imageNamed:self.isAllSel?@"common_sel":@"common_nor"] forState:UIControlStateNormal];

    for (WeddingCarCartModel *model in self.dataArray) {
        
        if (model.isCanBuy == 1) {
            model.isSel = self.isAllSel;
        }
    }
    
    [self.tableview reloadData];
    [self calculatePrice];
}


- (void)calculatePrice {

    double totalMoney = 0;  //商品总价
    double intentionMoney = 0;  //意向金

    for (int i = 0; i < self.dataArray.count; i++) {
        WeddingCarCartModel *model = self.dataArray[i];

        if (model.isSel) {
            totalMoney = totalMoney + model.totalPrice;
        }
    }
    
    NSInteger depositType = self.intentionModel.depositType;
    double deposit = self.intentionModel.deposit;
    if (depositType == 1) {
        double dep = deposit*0.01;
        intentionMoney = dep * totalMoney;
    } else {
        intentionMoney = deposit;
    }
    
    if (deposit == 0 || intentionMoney == 0) {
        self.IntentionLab.hidden = YES;
    } else {
        self.IntentionLab.hidden = NO;
    }
    
    
    //富文本
    NSString *yixiangjin= @"意向金:";
    NSString *rmb = @"¥";
    NSString *money = [Utilities changeDoubleToString:intentionMoney];
    NSString *mix = [NSString stringWithFormat:@"%@%@%@",yixiangjin,rmb,money];
    
    NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithString:mix];
    NSRange yixiangjinRange = NSMakeRange(0, yixiangjin.length);
    NSRange rmbRange = NSMakeRange(yixiangjin.length ,rmb.length);
    NSRange moneyRange = NSMakeRange(yixiangjin.length + rmb.length ,money.length);

    // 设置字体大小
    [attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:yixiangjinRange];
    [attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:rmbRange];
    [attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:15] range:moneyRange];

    [attrStr addAttribute:NSForegroundColorAttributeName value:UIColor.blackColor range:yixiangjinRange];
    [attrStr addAttribute:NSForegroundColorAttributeName value:UIColor.redColor range:rmbRange];
    [attrStr addAttribute:NSForegroundColorAttributeName value:UIColor.redColor range:moneyRange];

    
    self.IntentionLab.attributedText = attrStr;
    
    self.totalLab.text = [NSString stringWithFormat:@"合计:¥%@",[Utilities changeDoubleToString:totalMoney]];
    
    if (self.dataArray.count == 0) {
        self.IntentionLab.hidden = YES;
    }
}

#pragma mark UITableviewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [WeddingCarCartCell calculateHeightWithModel:self.dataArray[indexPath.section]];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    WeddingCarDetailViewController *vc = [[WeddingCarDetailViewController alloc] init];
    vc.packageId = self.dataArray[indexPath.section].goodsId;
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (self.dataArray[section].isNoti) {
        if ([self.dataArray[section].goodsMold isEqualToString:@"1"]) {
            return 32;
        }else if ([self.dataArray[section].goodsMold isEqualToString:@"3"]) {
            return CGFLOAT_MIN;
        }
    } else {
        return CGFLOAT_MIN;
    }
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 5;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    WeddingCarCartNotiHeader *headView = [[NSBundle mainBundle] loadNibNamed:@"WeddingCarCartNotiHeader"owner:nil options:nil].firstObject;
    return headView;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    WeddingCarCartCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WeddingCarCartCellID"];
    cell.selectionStyle =UITableViewCellSelectionStyleNone;
    [cell fillCellWithModel:self.dataArray[indexPath.section]];
    
    WEAKSELF
    cell.WeddingCarCartCellBlock = ^(WeddingCarCartCellActionType type) {
      
        switch (type) {
            case WeddingCarCartCellActionType_sel:{
                
                if (weakSelf.dataArray[indexPath.section].isCanBuy != 1) {
                    return;
                }
                
                weakSelf.dataArray[indexPath.section].isSel = !weakSelf.dataArray[indexPath.section].isSel;
                
                NSInteger count = 0;
                for (WeddingCarCartModel *model in weakSelf.dataArray) {
                    if (model.isSel) {
                        count++;
                    }
                }
                //全选
                [weakSelf refreshSelAllBtnStatus];
                
            }  break;
            case WeddingCarCartCellActionType_cut:{
                
                if (weakSelf.dataArray[indexPath.section].goodsNum > 1) {
                    weakSelf.dataArray[indexPath.section].goodsNum--;
                    
                    weakSelf.dataArray[indexPath.section].totalPrice = [weakSelf calaulatePriceWithModel:weakSelf.dataArray[indexPath.section]];
                    weakSelf.dataArray[indexPath.section].isNoti = [weakSelf refreshNotiStatusWithModel:weakSelf.dataArray[indexPath.section]];

                    [weakSelf request_updateCartWithIndex:indexPath.section];
                }
            }  break;
            case WeddingCarCartCellActionType_add:{
                
                weakSelf.dataArray[indexPath.section].goodsNum++;
                weakSelf.dataArray[indexPath.section].totalPrice = [weakSelf calaulatePriceWithModel:weakSelf.dataArray[indexPath.section]];
                weakSelf.dataArray[indexPath.section].isNoti = [weakSelf refreshNotiStatusWithModel:weakSelf.dataArray[indexPath.section]];

                
                [weakSelf request_updateCartWithIndex:indexPath.section];
            }  break;
            default:
                break;
        }
        
        [weakSelf calculatePrice];
        [weakSelf.tableview reloadData];
    };
    
    return cell;
}


#pragma mark 左滑删除
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    return YES;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {

    }
}

- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    WEAKSELF
    UITableViewRowAction *deleteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull deleteIndexPath) {
        [weakSelf request_deleteCartWithIndex:indexPath.section];
    }];

    deleteRowAction.backgroundColor = UIColorHex(0xFF2442);    
    return @[deleteRowAction];
}

- (NSMutableArray<WeddingCarCartModel *> *)dataArray {
    if (!_dataArray) {
        _dataArray = @[].mutableCopy;
    }
    return _dataArray;
}

- (void)request_cart {
    
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_CarCart];
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:[TTUserModel sharedObject].userId forKey:@"userId"];
    [dic setValue:@"2" forKey:@"isDel"];
    [dic setValue:self.storeId forKey:@"sellerId"];

    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在加载"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [SVProgressHUD dismiss];
        [[TTNoResultManager shareManager] hideNoResultWithView:weakSelf.tableview];

        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                
                NSDictionary *resultDic = [data valueForKey:@"data"];
                NSDictionary *sellerDeposit = [resultDic valueForKey:@"sellerDeposit"];
                weakSelf.intentionModel = [CommonIntentionModel modelWithJSON:sellerDeposit];
                
                NSArray *list = [resultDic valueForKey:@"userShoppingCarCarts"];
                if ([list isKindOfClass:[NSArray class]]) {
                    weakSelf.dataArray = @[].mutableCopy;
                    NSInteger validCount = 0;

                    for (int i = 0; i < list.count; i++) {
                        NSDictionary *listDic = list[i];
                        
                        if ([listDic isKindOfClass:[NSDictionary class]]) {
                            WeddingCarCartModel *model = [WeddingCarCartModel modelWithDictionary:list[i]];
                            model.isSel = NO;
                            model.totalPrice = [weakSelf calaulatePriceWithModel:model];
                            model.isNoti = [weakSelf refreshNotiStatusWithModel:model];
                            
                            if (model.isCanBuy == 1) {
                                validCount++;
                            }
                            
                            [weakSelf.dataArray addObject:model];
                        }
                    }
                    weakSelf.validCount = validCount;
                    
                    if (weakSelf.dataArray.count == 0) {
                        if (weakSelf.tableview) {
                            [[TTNoResultManager shareManager] showNoResultWithStateInView:weakSelf.tableview errorCode:kTTViewState_NoCart btnTitle:@"" didPressButton:^{}];
                        }
                    }
                    [weakSelf calculatePrice];
                    [weakSelf.tableview reloadData];
                }
            }
        }

        
    } FailedBlock:^(NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
    }];
}

- (double)calaulatePriceWithModel:(WeddingCarCartModel *)model {
    double platformPrice = model.platformPrice;
    
    if ([model.goodsMold isEqualToString:@"1"]) {

        if (model.goodsNum > model.defaultNum) {
            platformPrice = platformPrice + (model.goodsNum - model.defaultNum)*model.followPrice;
        } else {
            platformPrice = platformPrice;
        }
        
    } else if ([model.goodsMold isEqualToString:@"3"]) {
        platformPrice = model.platformPrice * model.goodsNum;
    }
    return platformPrice;
}

- (BOOL)refreshNotiStatusWithModel:(WeddingCarCartModel *)model {
    if (model.goodsNum > model.defaultNum) {
        return NO;
    } else {
        return YES;
    }
}

- (void)request_deleteCartWithIndex:(NSInteger)index {

    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:self.dataArray[index].uscId forKey:@"uscId"];
    [dic setValue:@"1" forKey:@"isDel"];
    [dic setValue:[TTUserModel sharedObject].userId forKey:@"userId"];
    [dic setValue:self.storeId forKey:@"sellerId"];
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_UpdateCarCart];
    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在删除"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                [weakSelf request_cart];
            }
        }
    } FailedBlock:^(NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
    }];
}

- (void)request_updateCartWithIndex:(NSInteger)index {
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:self.dataArray[index].uscId forKey:@"uscId"];
    [dic setValue:@(self.dataArray[index].goodsNum) forKey:@"goodsNum"];
    [dic setValue:[TTUserModel sharedObject].userId forKey:@"userId"];
    [dic setValue:self.storeId forKey:@"sellerId"];
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_UpdateCarCart];
    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在更新车队数据"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
//                [weakSelf request_cart];
            }
        }
    } FailedBlock:^(NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
    }];
}

- (void)request_collectWithIndex:(NSInteger)index {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    
    [dic setValue:self.dataArray[index].goodsId forKey:@"baseId"];
    [dic setValue:@(4) forKey:@"collectType"];
    [dic setValue:[TTUserModel sharedObject].userId forKey:@"userId"];
    
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_AddCollect];
    
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                
                [SVProgressHUD showSuccessWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
            } else {
               [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
               [SVProgressHUD dismissWithDelay:1];
           }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
    }];
    
}

@end
